package com.livestocksolutions.ui;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.WindowConstants;

import com.livestocksolutions.LivestockSolutions;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 * Show the progress of the Archive activity to the user.
 * @author Ken DeVries
 * @author Adam Parr
 * 
 * @.modified 26 September 2012
 */
public class ArchiveFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	private final JProgressBar archiveProgress = new JProgressBar();
	private final JButton closeWindow = new JButton("Close");
	private final JLabel archiveLabel = new JLabel("Archiving...");
	private boolean running=true;
	private boolean success=false;
	
	/**
	 * Constructor.
	 */
	public ArchiveFrame(){
		setTitle("Archive");
		setIconImage(MainFrame.getImage(MainFrame.APP_ICON));
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		archiveLabel.setHorizontalAlignment(SwingConstants.CENTER);
		add(archiveLabel);
		add(archiveProgress, BorderLayout.SOUTH);
		setSize(300,100);
		setLocationRelativeTo(null);
		setMinimumSize(new Dimension(300,100));
		archiveProgress.setIndeterminate(true);
		archiveProgress.setValue(0);
		setVisible(true);
	}
	
	/**
	 * Start the Archive action and display progress and any errors to the user.
	 */
	public void start(){
		running=true;
		
		new Thread(){
			@Override
			public void run(){
				while(running){
					try {
						sleep(50);
					} catch (InterruptedException e) {}
					int percent = LivestockSolutions.getProgress();
					percent=percent<0||percent>100?100:percent;
					archiveLabel.setText("Archiving... ("+percent+"%)");
					archiveProgress.setValue(percent);
				}
				setVisible(false);
				String result="";
				if(success){
					result="Archiving Complete<br>";
				}else{
					result="Archival Failed<br>";
				}
				archiveLabel.setText("<html><body style=\"text-align:center\">"+result+LivestockSolutions.getMessage()+"</body></html>");
				ArchiveFrame.this.remove(archiveProgress);
				JPanel closePanel = new JPanel();
				closePanel.add(closeWindow, BorderLayout.CENTER);
				add(closePanel, BorderLayout.SOUTH);
				setVisible(true);

				closeWindow.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e){
						interrupt();
						dispose();
					}
				});
			}
		}.start();
		archiveProgress.setIndeterminate(false);
		new Thread(){
			@Override
			public void run(){
				success=LivestockSolutions.archive();
				running = false;
			}
		}.start();
	}
}
